import "./index.scss";
import MonthCalendar from "./MonthCalendar";
import Header from "./Header";
import dayjs, { Dayjs } from "dayjs";
import cs from "classnames";
import { CSSProperties, ReactNode, useState } from "react";
import LocaleContext from "./LocaleContext";
import useMergeState from "../utils/useMergeState";

export type CalendarProps = {
  value: Dayjs;
  defaultValue?: Dayjs;
  style?: CSSProperties;
  className?: string;
  dateRange?: (currentDate: Dayjs) => ReactNode;
  dateInnerContent?: (currentDate: Dayjs) => ReactNode;
  // 国际化 
  locale?: string;
  onChange?: (date: Dayjs) => void;
};

function Calendar(props: CalendarProps) {
  const {
    value,
    defaultValue,
    style,
    className,
    locale,
    // allowSelect = true,
    // todayButton = true,
    dateRange,
    dateInnerContent,
    onChange,
  } = props;
  const [curValue, setCurValue] = useState<Dayjs>(value);
  const [curMonth, setCurMonth] = useState<Dayjs>(value);

  const classNames = cs("calendar", className);

  function selectHandler(date: Dayjs) {
    _changeDate(date);
  }

  function prevMonthHandler() {
    setCurMonth(curMonth.subtract(1, "month"));
  }

  function nextMonthHandler() {
    setCurMonth(curMonth.add(1, "month"));
  }

  function _changeDate(date: Dayjs) {
    setCurValue(date);
    setCurMonth(date);
    onChange?.(date);
  }

  function todayHandler() {
    const date = dayjs();

    _changeDate(date);
  }

  return (
    <LocaleContext.Provider value={{ locale: locale || navigator.language }}>
      <div className={classNames} style={style}>
        <Header
          curMonth={curMonth}
          todayHandler={todayHandler}
          prevMonthHandler={prevMonthHandler}
          nextMonthHandler={nextMonthHandler}
        />
        <MonthCalendar
          {...props}
          value={curValue}
          curMonth={curMonth}
          selectHandler={selectHandler}
        ></MonthCalendar>
      </div>
    </LocaleContext.Provider>
  );
}

export default Calendar;
